<template>
    <div>
        <div>
            <table v-if="addressList.length > 0">
                <thead>
                    <tr>
                        <th>是否默认</th>
                         <th>收件人</th>
                         <th>收件人电话</th>
                        <th>地址</th>
                        <th>创建时间</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="userAddress in addressList" :key="userAddress.id">
                         <td>
                            <input type="radio" :value="userAddress.id" v-model="defaultAddressId"
                                @change="setDefault(userAddress.id)" />
                        </td>
                        <td>{{ userAddress.name }}</td>
                        <td>{{ userAddress.phone }}</td>
                       
                        <td>{{ formatAddress(userAddress) }}</td>
                        <td>{{ userAddress.createTime }}</td>
                        <td>{{ userAddress.remark }}</td>
                        <td>
                            <button @click="editAddress(userAddress)" class="btn-modify">编辑</button>
                            <button @click="delAddress(userAddress.id)" class="btn-delete">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>

            <div v-else>
                <p>暂无地址数据,请先去添加</p>
            </div>
            <div>
                <span>共 {{ addressList.length }} 条记录</span>
            </div>
        </div>
        <button @click="back()">返回</button>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const addressList = ref([])
const defaultAddressId = ref(null)

const userId = window.sessionStorage.getItem('id')

// 地址
const searchAddress = async () => {
   
    console.log('用户ID:', userId)
    const response = await axios.get('api/getUserAddressList', {
        params: { userId: userId }
    })
    addressList.value = response.data.userAddressList
    console.log('地址列表:', addressList.value);
    
    
    // 查找默认
    const defaultAddress = addressList.value.find(userAddress => userAddress.isDefault)
    if (defaultAddress) {
        defaultAddressId.value = defaultAddress.id
    }
}

// 格式化地址显示
function formatAddress(userAddress) {
    if (!userAddress || !userAddress.address) return '';
    const parts = userAddress.address.split(' ');
    if (parts.length >= 4) {
        return parts[0] + "省" + parts[1] + "市" + parts[2] + "区" + parts[3];
    }
    return userAddress.address;
}

// 设置默认
const setDefault = async (id) => {

    const response = await axios.get('api/updateIsDefault', { 
        params: { 
            id: id ,
            userId: userId
        } 
    })
    if (response.data.code === 5200) {
        searchAddress()
        window.dispatchEvent(new Event('addressUpdated'))
    } else {
        alert('设置默认地址失败')
    }

}

// 编辑地址
const editAddress = (userAddress) => {
    console.log(userAddress);
    
    router.push({
        path: '/updateAddress',
        query: {
           id : userAddress.id,
        }
    })
}

// 删除地址
const delAddress = async (id) => {
    if (confirm('确定要删除该地址吗？')) {

        const response = await axios.get('api/deleteUserAddress', {
            params: {id: id }
         })

        console.log(response.data)
        if (response.data.code === 5200) {
            alert('删除成功')
            searchAddress()
        } else {
            alert('删除失败:')
        }

    }
}
const back = () => {
    router.back()
}

onMounted(() => {
    searchAddress()
})
</script>

<style scoped>
table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;

}

th,td {
    border: 1px solid #ddd;
    padding: 12px;
    text-align: center;
}

th {
    font-weight: bold;
    color: #555;
}

div[v-else] {
    padding: 40px 20px;
    text-align: center;
    border-radius: 8px;

}

div[v-else] p {
    font-size: 18px;
    color: #666;
    margin: 0;
}

div:last-child {
    padding: 15px 20px;
    text-align: right;
}

</style>